package com.hjj.controller;

import com.hjj.beans.Stu;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/stu")
public class StuController {

    @RequestMapping("get.action")
    public Map<String, Object> get(@Valid Stu stu, BindingResult bindingResult){
        HashMap<String, Object> hashMap = new HashMap<>();
        if (bindingResult.hasErrors()){
            hashMap.put("result", "error");

            ArrayList<Object> arrayList = new ArrayList<>();

            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                HashMap<String, Object> errorMsg = new HashMap<>();
                errorMsg.put("fieldName", fieldError.getField());
                errorMsg.put("rejectedValue", fieldError.getRejectedValue());
                errorMsg.put("defaultMessage", fieldError.getDefaultMessage());

                arrayList.add(errorMsg);
            }

            arrayList.add(fieldErrors);

            hashMap.put("message", arrayList);


            return hashMap;
        }

        hashMap.put("result", "success");
        hashMap.put("data", stu);

        return hashMap;
    }
}
